package alo.p11.work;

import alo.p10.HeapSort;

/**
 * @ClassName TwoElementWithMinSum
 * @Description 查找和最接近0的两个元素
 * @Author Fanxc
 * @DATE 2021/3/12 20:34
 * @Version 1.0
 */
public class TwoElementWithMinSum {
    void twoElementWithMinSum(int[] A,int n){
        int min_sum,sum,min_i,min_j,inv_count=0;
        if (n<2){
            System.out.println("无效数组");
            return;
        }

        min_i=0;
        min_j=1;
        min_sum=A[0]+A[1];
        for (int i = 0; i < n - 1; i++) {
            for (int j = i+1; j < n; j++) {
                sum=A[i]+A[j];
                if (Math.abs(min_sum)>Math.abs(sum)){
                    min_sum=sum;
                    min_i=i;
                    min_j=j;
                }

            }
        }
        System.out.println("The two number are "+A[min_i]+"  and  "+A[min_j]);
    }

    void twoElementWithMinSum2(int[] A,int n){
        int i=0,j=n-1,temp,positiveClosest=Integer.MAX_VALUE,negativeClosest=Integer.MIN_VALUE;
        int p_i=-1,p_j=-1;
        int n_i=-1,n_j=-1;

        new HeapSort().heapSort(A,0,n-1);
        while (i<j){
            temp=A[i]+A[j];
            if (temp>0) {
                if (temp < positiveClosest) {
                    positiveClosest = temp;
                    p_i=i;
                    p_j=j;
                    j--;
                }
            }else if (temp<0){
                if (temp>negativeClosest){
                    negativeClosest=temp;
                    n_i=i;
                    n_j=j;
                    i++;
                }
            }else {
                System.out.println("Closest Sum"+A[i]+"  and  "+A[j]);
            }
        }
        if (Math.abs(negativeClosest)>positiveClosest){
            System.out.println("Closest Sum"+A[p_i]+"  and  "+A[p_j]);
        }else {
            System.out.println("Closest Sum"+A[n_i]+"  and  "+A[n_j]);
        }
    }
}
